<!--仪表盘预览、编辑-->
<template>
    <div :class="{TemplateIndex:true,'wly-page':true,isFull}">
        <el-container>
            <el-header
                style="border-bottom: 1px solid #ccc;display: flex;justify-content: space-between;align-items: center"
                height="40px">
                <div>
                    <el-button icon="el-icon-back" type="text" v-if="isEdit" @click="() => $router.back()">返回</el-button>
                    <span>{{board.name||'未定义'}}-{{isEdit?'编辑':'预览'}}</span>
                </div>

                <div v-if="boardId" class="btn-group">
                    <template v-if="isEdit">
                        <el-button type="text" icon="el-icon-circle-plus" @click="addComponent">添加组件</el-button>
                        <el-dropdown trigger="click">
                            <el-button type="text" icon="el-icon-scissors">组件过滤</el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item icon="el-icon-circle-plus" @click.native="openFilter(1)">过滤日期
                                </el-dropdown-item>
                                <el-dropdown-item icon="el-icon-circle-plus" @click.native="openFilter(2)">数值区间
                                </el-dropdown-item>
                                <el-dropdown-item icon="el-icon-circle-plus" @click.native="openFilter(3)">文本下拉
                                </el-dropdown-item>
                                <el-dropdown-item icon="el-icon-circle-plus" @click.native="openFilter(4)">数值下拉
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                        <el-button type="text" icon="el-icon-folder-checked" @click="savePanelInfo">保存</el-button>
                    </template>
                    <el-button v-else type="text" icon="el-icon-edit" @click="gotoEdit">编辑</el-button>
                    <el-button icon="el-icon-full-screen" type="text" @click="isFull =!isFull">{{isFull ? '取消':''}}全屏</el-button>
                </div>
            </el-header>
            <el-main ref="panelContainer" style="overflow: auto;height:100%;width: 100%;padding: 0"
                     v-loading="loading" element-loading-text="正在加载" element-loading-spinner="el-icon-loading">
                <div :class="['component-parent',[{hasBg:isEdit}]]">
                    <template v-for="(item,index) in includeList">
                        <vue-draggable-resizable v-if="item.unitId"
                                                 :class="{'my-com':true,'preview':!isEdit,'max':!!item.max}"
                                                 :key="item.unitId"
                                                 :w=parseInt(item.width||200)
                                                 :h=parseInt(item.length||200)
                                                 :x=parseInt(item.haxis||0)
                                                 :y=parseInt(item.vaxis||0)
                                                 :scroll-sensitivity="150"
                                                 :force-fallback="false"
                                                 :min-width="200"
                                                 :min-height="200"
                                                 :snapTolerance="10"
                                                 :draggable="!!isEdit"
                                                 :resizable="!!isEdit"
                                                 :snap="true"
                                                 :parent="true"
                                                 :isConflictCheck="false"
                                                 @dragging="(x, y) => onDrag(item, x, y)"
                                                 @resizing="(x, y,w,h) => onResize(item,x, y,w,h)"
                                                 @refLineParams="getRefLineParams">
                            <el-container>
                                <el-header class="component-head">
                                    <span style="font-weight: bold">{{item.titleId}}</span>
                                    <div>
                                        <i class="el-icon-scissors" v-if="item.filterList.length !==0" @click="openFullFilter(item)"></i>
                                        <el-dropdown trigger="hover">
                                            <i class="el-icon-setting" v-if="isEdit"></i>
                                            <el-dropdown-menu slot="dropdown">
                                                <el-dropdown-item icon="el-icon-edit"
                                                                  @click.native="openUpNameDialog(item)">编辑名称
                                                </el-dropdown-item>
                                                <el-dropdown-item icon="el-icon-edit-outline"
                                                                  @click.native="editFilter(item)">编辑组件
                                                </el-dropdown-item>
                                                <el-dropdown-item icon="el-icon-delete" @click.native="deleteFilter(item)">
                                                    删除组件
                                                </el-dropdown-item>
                                                <el-dropdown-item icon="el-icon-scissors" @click.native="filterConfig(item)">
                                                    配置过滤条件
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </el-dropdown>
                                        <i class="el-icon-full-screen" @click="componentFull(item)"></i>
                                    </div>
                                </el-header>
                                <el-main style="padding: 0;overflow: hidden">
<!--                                    <div :class="{filter:true,showFilter:item.showFilter}">-->
<!--                                        &lt;!&ndash; 图形组件所属的过滤组件&ndash;&gt;-->
<!--                                        <div v-for="filterItem in item.filtCom" class="filter-item" :key="filterItem.unitId">-->
<!--                                            <component class="filter-item-form" :is="filterItem.unitCom" :numIntervalValue="filterItem" :key="filterItem.unitId"-->
<!--                                                       :updatePickerValue="filterItem"-->
<!--                                                       :option="filterItem"-->
<!--                                                       :parameter="{status:'1',unitId: filterItem.unitId,selectValue: filterItem.value}"-->
<!--                                                       @getDateFlag="saveFilterFlag(item.unitId)"-->
<!--                                                       @successFlag="saveFilterFlag(item.unitId)"-->
<!--                                                       @getNumFlag="saveFilterFlag(item.unitId)">-->
<!--                                            </component>-->
<!--                                            <el-dropdown trigger="hover">-->
<!--                                                <i class="el-icon-setting"  v-if="isEdit"></i>-->
<!--                                                <el-dropdown-menu slot="dropdown">-->
<!--                                                    <el-dropdown-item icon="el-icon-edit-outline"-->
<!--                                                                      @click.native="editFilter(filterItem)">编辑过滤-->
<!--                                                    </el-dropdown-item>-->
<!--                                                    <el-dropdown-item icon="el-icon-delete"-->
<!--                                                                      @click.native="deleteFilter(filterItem,item.unitId)">删除过滤-->
<!--                                                    </el-dropdown-item>-->
<!--                                                </el-dropdown-menu>-->
<!--                                            </el-dropdown>-->
<!--                                        </div>-->
<!--                                        <div style="text-align: right">-->
<!--                                            <el-button type="text" size="mini" @click="item.showFilter = false">收起</el-button>-->
<!--                                        </div>-->
<!--                                    </div>-->
                                    <!-- 图形组件-->
                                    <component :is="item.unitCom" :numIntervalValue="item"
                                               :updatePickerValue="item"
                                               :option="item"
                                               :key="item.key"
                                               :parameter="{status:'1',unitId: item.unitId,selectValue: item.value}"
                                               :ref="'unitId'+item.unitId">
                                    </component>
                                </el-main>
                            </el-container>
                            <!--辅助线-->
                            <span class="ref-line v-line"
                                  v-for="item1 in vLine"
                                  v-show="item1.display"
                                  :style="{ left: item1.position, top: item1.origin, height: item1.lineLength}"
                            />
                            <span class="ref-line h-line"
                                  v-for="item2 in hLine"
                                  v-show="item2.display"
                                  :style="{ top: item2.position, left: item2.origin, width: item2.lineLength}"
                            />
                            <!--辅助线END-->
                        </vue-draggable-resizable>
                    </template>
                </div>
            </el-main>
        </el-container>
        <time-filter-component ref="timeFilter" @getFilterFlag="filterEditSuccess"></time-filter-component>
        <numerical-range-component ref="numericalRange" @getFilterFlag="filterEditSuccess"></numerical-range-component>
        <text-drop-component ref="textDrop" @getFilterFlag="filterEditSuccess"></text-drop-component>
        <value-drop-component ref="valueDrop" @getFilterFlag="filterEditSuccess"></value-drop-component>
        <edit-name-dialog ref="nameDialog" @changeUnitName="getUpName"></edit-name-dialog>
        <el-dialog
            :title="curPanelData?curPanelData.titleId+' 过滤条件 ':''"
            :visible.sync="filtersVisible"
            width="50%"
            top="0">
            <div v-if="curPanelData" class="filter-container">
                <template v-for="filterItem in curPanelData.filterList">
                    <custom-input :key="filterItem.key" :label="filterItem.fieldName" :config="filterItem"  v-model="listQuery[curPanelData.unitId][filterItem.linkField]"
                                  v-if="['Input'].includes(filterItem.filterComType)"></custom-input>
                    <custom-select :key="filterItem.key" :label="filterItem.fieldName" :config="filterItem" v-model="listQuery[curPanelData.unitId][filterItem.linkField]"
                                   v-if="['Select'].includes(filterItem.filterComType)"></custom-select>
                    <custom-date :key="filterItem.key" :label="filterItem.fieldName" :config="filterItem" v-model="listQuery[curPanelData.unitId][filterItem.linkField]"
                                 v-if="['DatePicker'].includes(filterItem.filterComType)"></custom-date>
                </template>
                <el-button type="primary" size="small">查询</el-button>
            </div>
            <div style="text-align: right">
                <el-button type="text" size="mini" @click="filtersVisible = false">收起</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import ajax from '@api/ajax'
import { QUERY_PANEL_INFO, SAVE_PANEL_INFO, SAVE_PANEL_INFO_List, } from '@api/url'
import VueDraggableResizable from 'vue-draggable-resizable-gorkys'
import 'vue-draggable-resizable-gorkys/dist/VueDraggableResizable.css'
import 'vue-draggable-resizable/dist/VueDraggableResizable.css'
import VHeader from '../../../components/VHeader/VHeader'
import DateFilterComponent from '../../../components/fliterComponent/DateFilterComponent'
import NumIntervalComponent from '../../../components/fliterComponent/NumIntervalComponent'
import NumMultipleComponent from '../../../components/fliterComponent/NumMultipleComponent'
import NumRadioComponent from '../../../components/fliterComponent/NumRadioComponent'
import TextMultipleComponent from '../../../components/fliterComponent/TextMultipleComponent'
import TextRadioComponent from '../../../components/fliterComponent/TextRadioComponent'
import CommonComponent from './commoncompents/CommonComponent'
import NumericalRangeComponent from './filtercompents/NumericalRangeComponent'
import TextDropComponent from './filtercompents/TextDropComponent'
import TimeFilterComponent from './filtercompents/TimeFilterComponent'
import ValueDropComponent from './filtercompents/ValueDropComponent'
import EditNameDialog from './filtermodel/EditNameDialog'
import FilterModel from './filtermodel/FilterModel'
import CustomInput from "@/views/useHome/components/customInput";
import CustomSelect from "@/views/useHome/components/customSelect";
import CustomDate from "@/views/useHome/components/customDate";
import {GET_MODEL_COL} from "../../../api/url";

    export default {
        name: 'TemplateIndex',
        props: {
            boardId: {// 仪表盘id
                type: String,
                default: ''
            },
            isEdit: { // 是否是编辑状态
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                loading:false,
                filtersVisible:false,
                curPanelData:null,
                isFull:false,
                board:{},
                vLine: [],
                hLine: [],
                includeList: [],
                filterList:[], // 过滤组件
                panelLists: [],
                filterUnitList: [
                    {
                        unitId: '',
                        unitName: '',
                        boardId: '',
                        value: '',
                        unitType: '',
                        titleId: '', // 标题
                        haxis: '', // 横轴初始化
                        vaxis: '', // 纵轴初始化
                        width: '', // 宽度
                        length: '' // 高度
                    }
                ],
                listQuery:{}
            }
        },
        watch: {
            boardId(v) {
                if (v) {
                    this.qryPanel()
                    this.updateBoard()
                }
            },
        },

        methods: {
            // 组价全屏
            componentFull(item){
                item.max = !item.max
                if(item.max){
                    sessionStorage.setItem('tempWH',`${item.width}-${item.length}`)
                    item.width = document.documentElement.clientWidth
                    item.length = document.documentElement.clientHeight
                }else{
                    const wh = sessionStorage.getItem('tempWH')||'0-0'
                    const WHNumber = wh.split('-')
                    item.width = Number(WHNumber[0])
                    item.length = Number(WHNumber[1])
                }
                // this.$refs['unitId'+item.unitId][0].resize()
            },
            // 打开过滤
            openFullFilter(item){
                item.showFilter = !item.showFilter
                this.curPanelData = item
                this.$set(this.listQuery,item.unitId, {});
                this.filtersVisible = true
                this.$forceUpdate();
            },
            updateBoard(){
                const temp = sessionStorage.getItem('curBoard')
                if(temp){
                    this.board =  JSON.parse(temp)
                }
            },
            // 辅助线回调事件
            getRefLineParams(params) {
                const {vLine, hLine} = params
                this.vLine = vLine
                this.hLine = hLine
            },
            gotoEdit() {
                this.$router.push({name: 'PanelEdit',query:{boardId:this.boardId}})
            },
            savePanelInfo() {
                // 保存仪表盘所有组件位置信息
                // 因为获取数据时，仪表盘数据时扁平的，前端转化为父子关系，保存时，需要恢复成扁平数据
                const _temp = []
                this.includeList.forEach(item => {
                    // const filtCom = item.filtCom
                    // delete item.filtCom
                    _temp.push(item)
                    // filtCom.forEach(filt => {
                    //     if(_temp.findIndex(te =>te.unitId === filt.unitId) === -1){
                    //         _temp.push(filt)
                    //     }
                    // })
                })
                ajax.post(SAVE_PANEL_INFO_List, _temp).then(res => {
                    this.$message.success('保存成功！')
                    this.$router.push({name:'PanelIndex',query:{boardId:this.boardId}})
                })
            },
            // 改变组件位置的方法
            onDrag(item, x, y) {
                this.includeList = this.includeList.map(ele => {
                    if (ele.unitId === item.unitId) {
                        ele.haxis = x;
                        ele.vaxis = y;
                    }
                    return ele
                })

                // ajax.post(SAVE_PANEL_INFO_List, this.includeList).then(res => {
                // }).catch(err => {
                //     console.error('加载出错！', err)
                // }).finally(() => {
                // })
            },
            onResize(item, x, y, w, h) {
                console.log(w, h)
                this.includeList.forEach(ele => {
                    if (ele.unitId === item.unitId) {
                        ele.haxis = x;
                        ele.vaxis = y;
                        ele.width = w
                        ele.length = h
                    }
                })

                // ajax.post(SAVE_PANEL_INFO_List, this.includeList).then(res => {
                // }).catch(err => {
                //     console.error('加载出错！', err)
                // }).finally(() => {
                // })
            },
            // 弹出修改名称框
            openUpNameDialog(item) {
                this.$refs.nameDialog.openEditName(item)
            },
            getUpName(value) {
                this.includeList.forEach(ele => {
                    if (ele.unitId === value.unitId) {
                        ele.titleId = value.upName
                    }
                })
                // for (let i = 0; i < this.includeList.length; i++) {
                //     let item = this.includeList[i]
                //     if (item.haxis2 !== null && item.vaxis2 !== null) {
                //         item.haxis = item.haxis2
                //         item.vaxis = item.vaxis2
                //     }
                // }
                ajax.post(SAVE_PANEL_INFO_List, this.includeList).then(res => {
                }).catch(err => {
                    console.error('加载出错！', err)
                }).finally(() => {
                })
            },
            // 打开对应过滤组件的页面
            openFilter(type) {
                switch (type) {
                    // 时间过滤组件
                    case 1:
                        this.$refs.timeFilter.openView(this.boardId)
                        break
                    // 数值过滤组件
                    case 2:
                        this.$refs.numericalRange.openView(this.boardId)
                        break
                    // 文本下拉过滤组件
                    case 3:
                        this.$refs.textDrop.openView(this.boardId)
                        break
                    // 数值下拉过滤组件
                    case 4:
                        this.$refs.valueDrop.openView(this.boardId)
                        break
                    // 默认
                    default:
                        this.$refs.timeFilter.openView(this.boardId)
                }
            },
            // 编辑组件
            editFilter(item) {
                let param = {
                    status: 'edit',
                    unitId: item.unitId,
                    boardId: this.boardId
                }
                switch (item.filterUnitType) {
                    // 时间过滤组件
                    case '1':
                        this.$refs.timeFilter.editPanel(param)
                        break
                    // 数值过滤组件
                    case '2':
                        this.$refs.numericalRange.editPanel(param)
                        break
                    // 文本下拉过滤组件
                    case '3':
                        this.$refs.textDrop.editPanel(param)
                        break
                    // 数值下拉过滤组件
                    case '4':
                        this.$refs.valueDrop.editPanel(param)
                        break
                    default:
                        this.$router.push({
                            name: 'CommonMain',
                            query: {
                                unitId: item.unitId,
                                boardId: this.boardId,
                            }
                        })
                }
            },
            // 删除组件
            deleteFilter(comData,pUnitId) {
                let param = {
                    optMode: 'D',
                    unitId: comData.unitId,
                    boardId: this.boardId
                }
                ajax.post(SAVE_PANEL_INFO, param).then(res => {
                    // 如果是删除过滤组件
                    if(comData.unitType === '2' &&  pUnitId){
                        this.includeList = this.includeList.map(EItem => {
                            if(EItem.unitId === pUnitId){
                                EItem.filtCom = EItem.filtCom.filter(FItem => FItem.unitId !== comData.unitId)
                                // 没有过滤组件了，收起
                                if(EItem.filtCom.length ===0){
                                    EItem.showFilter = false
                                }
                            }
                            return EItem;
                        })
                    }else{
                        this.includeList = this.includeList.filter(item=> item.unitId !== comData.unitId)
                    }
                })
            },
            // 配置过滤条件
            filterConfig(item){
                const {boardId,unitId} = item
                const query = {boardId,unitId}
                this.$router.push({name:'filterConfig',query:query})
            },
            // 添加组件
            addComponent() {
                let param = {
                    optMode: 'A',
                    titleId: '未命名组件',
                    unitCom: 'CommonComponent',
                    unitType: '1',
                    boardId: this.boardId,
                    haxis: '200',
                    vaxis: '200',
                    width: '500',
                    length: '400'
                }
                ajax.post(SAVE_PANEL_INFO, param).then(res => {
                    this.$router.push({
                        name: 'CommonMain',
                        query: {
                            unitId: res.data.unitId,
                            boardId: this.boardId,
                            pageFlag: '1'
                        }
                    })
                })
            },
            // 查询仪表盘
            qryPanel() {
                let param = {
                    boardId: this.boardId
                }
                const includeList = []
                const filterComponents = [];
                this.loading = true
                ajax.post(QUERY_PANEL_INFO, param).then(res => {
                    res.data.forEach(item => {
                        if(item.unitType === '1'){
                            item.openItem = false
                            item.hoverCard = false
                            // 坐标未定义则默认0，坐标小于0，也是0
                            item.haxis = item.haxis?item.haxis<0?0:item.haxis:0;
                            item.vaxis = item.vaxis?item.vaxis<0?0:item.vaxis:0;
                            item.showFilter = false
                            item.filterList = []
                            includeList.push(item)
                        }else if(item.unitType === '2'){
                            filterComponents.push(item)
                        }
                    })
                    this.includeList = [...includeList];
                    this.includeList.forEach((item,index) => {
                        this.findFilter(item.unitId,index)
                    })
                    // this.includeList = includeList.map(item => {
                    //     item.filtCom = filterComponents.filter(fItem => fItem.ctlUnit === item.unitId)
                    //     return item;
                    // })
                    // this.filterList = filterComponents
                }).finally(() => this.loading = false)
            },
            // 判断组件类型
            isCommonUnit(item) {
                if (item.unitType === '1') {
                    return item.unitId
                }
                return null
            },
            isFilterUnit(item) {
                if (item.unitType === '2') {
                    return item.unitId
                }
                return null
            },
            // 跨页面取参数
            getParams() {
                this.boardId = sessionStorage.getItem('boardId')
                this.qryPanel()
            },
            // 取组件内具体绑定值
            getUnitValue(item) {
                let value
                if (item.filterUnitType === '1') {
                    value = item.value.value[0]
                } else if (item.filterUnitType === '2') {
                    value = {
                        minvalue: item.value.minValue,
                        maxvalue: item.value.maxValue
                    }
                } else if (item.filterUnitType === '3' || item.filterUnitType === '4') {
                    value = item.value.value
                }
                return value
            },
            /**
             * 保存过滤条件回调
             * @param unitId 所绑定图形组件的unitId
             */
            saveFilterFlag(unitId) {
                if(unitId){
                    const refName = `unitId${unitId}`
                    console.log('刷新组件',refName)
                    this.$refs[refName][0].reload()
                }
            },
            // 过滤条件编辑成功回调
            filterEditSuccess() {
                this.qryPanel()
            },
            init(){
                this.$refs['panelContainer'].scrollTop = 0
            },
            findFilter(unitId,index){
                this.$http.post(GET_MODEL_COL,{modelId:unitId}).then(res => {
                    const {data:{data}} = res
                    if(!data) return
                    if(data.formula){
                        this.includeList[index].filterList = JSON.parse(data.formula)
                    }
                })
            }
        },
        components: {
            VHeader,
            VueDraggableResizable,
            TimeFilterComponent,
            FilterModel,
            DateFilterComponent,
            NumIntervalComponent,
            CommonComponent,
            NumMultipleComponent,
            NumRadioComponent,
            TextMultipleComponent,
            TextRadioComponent,
            NumericalRangeComponent,
            TextDropComponent,
            ValueDropComponent,
            EditNameDialog,
            CustomDate,
            CustomInput,
            CustomSelect
        }
    }
</script>

<style lang="stylus" rel="stylesheet/stylus">
    .filter-container {
        display: flex
        margin-bottom 10px
        flex-wrap wrap
        .label {
            margin-left 6px
        }

        .filter-input {
            width 240px
            margin-bottom 10px
        }
        button{
            height 40px
        }
    }
    .TemplateIndex
        height 99.9%
        position relative
        transition position 0.3s
        &.isFull{
            position fixed
            top 0
            left 0
            width 100%
            height 100%
            background-color white
            z-index 9999
        }
        .filter-item{
            display flex
            justify-content space-between
            align-items center
            padding-bottom 5px
            &:not(:first-child){
                margin-top 5px
            }
        }
        .btn-group{
            .el-button{
                margin-left 20px
            }
        }
        .component-parent {
            position relative
            width: 2000px;
            height: 2000px;
            &.hasBg{
                background: linear-gradient(-90deg, rgba(0, 0, 0, 0.1) 1px, transparent 1px) 0% 0% / 20px 20px, linear-gradient(rgba(0, 0, 0, 0.1) 1px, transparent 1px) 0% 0% / 20px 20px;
            }
            .component-head {
                height: 30px !important;
                padding 0 10px
                border-bottom: 1px solid rgb(204, 204, 204);
                display: flex;
                justify-content: space-between;
                align-items: center;
                background: #fee9ea;
                color: #e85660;
                i{
                    color: #e85660;
                }
            }
        }

        .el-card__body
            height 95%

        .el-container
            height 100%

            .el-aside
                height 97%

        .el-main {
            overflow-y auto
        }

        .mainCenter
            position: relative;
            overflow: auto;
            height: 92%;
            width: 98%;
            border: 1px solid #e0dddd;

        .el-icon-circle-plus-outline
            font-size 38px
            margin-left 20px

        .component-i
            color #1c87b8
            margin-left 20px
            font-style normal

        .set-list
            position absolute
            top 30px
            right 5px
            width 200px
            background-color #FFF
            z-index 222
            display block
            padding 10px 14px
            box-shadow 0 2px 4px 2px #e0dddd

            .oper-item
                padding-left 7px
                height 35px
                line-height 35px
                width 100%
                cursor pointer

                &:hover
                    border-bottom 1px solid #e0dddd

        .select-content
            display flex
            align-items center
            justify-content flex-end
            margin-top -20px

        .my-com {
            background:white;
            &.preview{
                border: 1px solid #F87071;
            }
            &.max{
                position: fixed;
                left: 0;
                top: 0;
                transform:translate(0, 0) !important;
                width: 100vw !important;
                height: 100vh !important;
                z-index: 1000 !important;
            }
            .el-main{
                position relative
                .filter{
                    position absolute
                    top -100%
                    width 100%
                    background-color rgba(255,255,255,0.8)
                    backdrop-filter blur(10px)
                    padding 10px
                    box-shadow 0 1px 2px #ccc
                    max-height 170px
                    overflow-y auto
                    transition top 0.5s
                    z-index: 1000;
                    &.showFilter{
                        top 0
                    }
                }
            }

        }

</style>
